package auth

import (
	"context"
	"fast-boot/app/api/wxapp/internal/svc"
	"fast-boot/app/api/wxapp/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/cachex"
	"fast-boot/common/globalkey"
	"fmt"
	"github.com/hwUltra/fb-tools/jwtx"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"time"
)

type BindLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBindLogic(ctx context.Context, svcCtx *svc.ServiceContext) BindLogic {
	return BindLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BindLogic) Bind(req types.BindReq) (resp *types.TokenResp, err error) {

	key := fmt.Sprintf(globalkey.CacheWxAppSessionKey, req.OpenId)
	c := cachex.NewStore(l.svcCtx.Config.Cache)
	var sessionKeyVal string
	if err := c.Cache.Get(key, &sessionKeyVal); err != nil {
		return nil, err
	}
	plainData, err := l.svcCtx.WxMiniApp.Decrypt(sessionKeyVal, req.EncryptedData, req.Iv)
	if err != nil {
		return nil, err
	}
	phoneNumber := plainData.PhoneNumber

	userInfo := model.UserModel{}
	userThirdInfo := model.UserThirdModel{}
	l.svcCtx.GormClient.GormDb.Where("mobile = ?", phoneNumber).First(&userInfo)
	l.svcCtx.GormClient.GormDb.Where("platform = 'wxapp' and openid = ?", req.OpenId).First(&userThirdInfo)

	if userInfo.Id == 0 {
		//注册用户
		userInfo.Mobile = phoneNumber
		if err := l.svcCtx.GormClient.GormDb.Transaction(func(tx *gorm.DB) error {
			if err := tx.Create(&userInfo).Error; err != nil {
				return err
			}
			if userThirdInfo.Uid == 0 {
				userThirdInfo.Uid = userInfo.Id
				if err := tx.Save(&userThirdInfo).Error; err != nil {
					return err
				}
			}
			return nil
		}); err != nil {
			return nil, err
		}
	}
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	token, _ := jwtx.NewJwtX(l.ctx, l.svcCtx.Config.JwtUserKey).GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, userInfo.Id)

	return &types.TokenResp{
		OpenID: req.OpenId,
		Token:  token,
	}, nil

}
